package sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sys.dao.RoleDao;
import sys.dao.TbUserDao;
import sys.entity.MenuEntity;
import sys.entity.PageData;
import sys.entity.RoleEntity;
import sys.entity.vo.Menu;
import sys.entity.vo.RoleVo;
import sys.service.RoleService;
import sys.utils.PageUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private  RoleDao dao;
    @Override
    public void add(RoleEntity entity) {
        Integer[] menuId = entity.getMenuId();
        RoleVo roleVo = new RoleVo();
        BeanUtils.copyProperties(entity,roleVo);
        dao.addRole(roleVo);
        for (Integer integer : menuId) {
            dao.addRidAndMid(roleVo.getId(),integer);
        }

    }

    @Override
    public void delete(RoleEntity entity) {
        dao.delete(entity);
    }

    @Override
    public void update(RoleEntity entity) {
        //删除中间表数据
        dao.deleteMenuByRoleId(entity.getId());
        //中间表维护
        Integer[] menuId = entity.getMenuId();
        RoleVo roleVo = new RoleVo();
        BeanUtils.copyProperties(entity,roleVo);
        dao.updateRole(roleVo);
        for (Integer integer : menuId) {
            dao.addRidAndMid(roleVo.getId(),integer);
        }
    }

    @Override
    public List<RoleEntity> select(RoleEntity entity) {
        List<RoleEntity> role = dao.select(entity);
        RoleEntity roleEntity = role.get(0);
        if (entity!=null){
        Integer[] menuId =  dao.selectMenuId(entity.getId());
        roleEntity.setMenuId(menuId);
        }
        return  role;
    }

    @Override
    public PageData<RoleEntity> likeSelect(RoleEntity entity) {
        PageData<RoleEntity> pageData = PageUtil.getPageData(entity, dao);
        //获取查询的结果集
        List<RoleEntity> result = pageData.getResult();
        //遍历集合
        for (RoleEntity roleEntity : result) {
            //根据角色id查询中间表的菜单名称
          List<Map>  menuName = dao.selectMenu(roleEntity.getId());
            roleEntity.setMenuName(menuName);
        }
        return pageData;
    }

    @Override
    public void exportExcel(RoleEntity entity, HttpServletResponse response) {

    }

}
